package com.shipwe.loans.ui.presenter

import com.shipwe.loans.pro.ShipwePresenter
import com.shipwe.loans.ui.view.IOrderRepayListView
import com.shipwe.loans.utils.helper.UserPointsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONArray
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/26 11:59
 * @Annotation：待还款 Presenter 实现
 */
class OrderRepayListPresenter(private val iView: IOrderRepayListView): ShipwePresenter(iView) {

    private val TYPE_POINTS_TIPS = "TYPE_POINTS_TIPS"//剩余积分使用提示
    private val TYPE_ORDER = "TYPE_ORDER"//订单
    private val TYPE_EMPTY = "TYPE_EMPTY"//空提示

    //选择的订单
    private var selectOrder: JSONObject? = null

    /**
     * 加载待还款订单表
     */
    fun loadOrderRepayListAction(){
        val orderList = ArrayList<JSONObject>()
        //剩余积分使用提示
        val pointItem = getOrderRepayPointsTipsItem()
        if (pointItem != null){
            orderList.add(pointItem)
        }

        //待还款订单列表
        val list = getOrderRepayList()
        if (list != null && list.size > 0){
            orderList.addAll(list)
        } else {
            orderList.add(getOrderRepayEmptyItem())
        }
        iView.showOrderRepayList(orderList)
    }

    /**
     * 剩余积分使用提示
     */
    private fun getOrderRepayPointsTipsItem(): JSONObject?{
        val userPoints = UserPointsHelper.getShipweUserPoints()
        if (userPoints == 0){
            return null
        }
        val item = JSONObject()
        item.put("itemType",TYPE_POINTS_TIPS)
        item.put("points","$userPoints")
        return item
    }

    /**
     * 没有待还款订单
     */
    private fun getOrderRepayEmptyItem(): JSONObject{
        val item = JSONObject()
        item.put("itemType",TYPE_EMPTY)
        return item
    }

    /**
     * 待还款订单列表
     */
    private fun getOrderRepayList(): ArrayList<JSONObject>?{
        val pData = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_PRODUCT)
        if (pData.isNotEmpty()){
            val pList = arrayListOf<JSONObject>()
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                //待还款
                if (status == "REPAYMENT"){
                    item.put("itemType",TYPE_ORDER)
                    item.put("isOpen",false)
                    pList.add(item)
                }
            }
            return pList
        }
        return null
    }

    /**
     * 设置点击的订单
     */
    fun setOrderRepaySelectOrder(order: JSONObject){
        this.selectOrder = order
    }
}